package com.ripplezjw.blog.controller;

import com.ripplezjw.blog.Service.UserService;
import com.ripplezjw.blog.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

@Controller
public class RegisterController {
    @Autowired
    UserService userService;

    @GetMapping("/register")
    public String register() {
        return "register";
    }

    @PostMapping("/registerTo")
    public String registerTo(User user, RedirectAttributes redirectAttributes , HttpServletRequest request) {
        System.out.println(user);
        int userId = userService.registerUser(user.getUsername(), user.getPassword());
        if (userId > 0) {
            // 注册成功
            user.setUserId(userId);
            request.getSession().setAttribute("user_info", user);
            return "redirect:/index";
        } else {
            // 注册失败
            redirectAttributes.addFlashAttribute("register_error_msg", "注册失败，请重新注册");
            return "redirect:/register";
        }
    }
}
